package cn.cloud.mqtt2redis.service;

import cn.cloud.mqtt2redis.configuration.mqtt.MqttGateway;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class MqttPublish {
    @Autowired
    private MqttGateway mqttGateway;
    @Autowired
    private RedisService redisService;
    public static boolean isGetProbeCompleted = false;

    private Logger logger = LoggerFactory.getLogger(getClass());

    //设备发现，程序启动请求一次
    public synchronized void device_discovery(){
        this.mqttGateway.sendToMqtt("", "Discovery/Request");
    }

    //设备组的probe文件请求
    public synchronized void publish_multi_device_probe() {
        logger.info("开始请求所有设备probe文件!");
        List<String> machine_list = this.redisService.get_machineID_from_redis();
        if(machine_list.size()>0){
            long startTime=System.currentTimeMillis();   //获取开始时间
            for(int index=0;index<machine_list.size();index++) {
                this.publish_single_device_probe(machine_list.get(index));
                try{
                    Thread thread = Thread.currentThread();
                    thread.sleep(20);//暂停20ms后程序继续执行,等待上一个设备的probe文件解析
                }catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            this.isGetProbeCompleted = true;
            long endTime=System.currentTimeMillis();   //获取开始时间
            logger.info("请求所有设备probe文件耗时: "+ (endTime-startTime) + "ms");
        }else {
            logger.info("设备列表为空!");
        }

    }

    //请求单个设备Probe文件，程序启动请求并解析一次
    public synchronized void publish_single_device_probe(String machineID){
        String topic = "Probe/Query/Request/"+machineID;
        this.mqttGateway.sendToMqtt("", topic);
    }

    //单个设备的G代码映射发布
    public synchronized void publish_progMap(String valid_machineID){
        String paramID = redisService.get_paramID_from_redis(valid_machineID,"PROGID_MAP");
        String topic = "Query/Request/"+valid_machineID;
        String payload = "{\"ids\":[{\"id\":\""+paramID+"\"}]}";
        logger.info("publish:request for progmap-"+valid_machineID);
        //logger.info("End push get_progMap scheduled! topic:"+topic+"; payload:"+payload);
        this.mqttGateway.sendToMqtt(payload,topic);
    }

    //所有设备的G代码文件映射请求发布
    public synchronized void request_progMap(){
        List<String> valid_machineID_list = this.redisService.get_validMachineID_from_redis();
        if(valid_machineID_list!=null && valid_machineID_list.size()>0) {
            for (String valid_machineID :valid_machineID_list) {
                publish_progMap(valid_machineID);
                try {
                    Thread.currentThread().sleep(20);//暂停20ms后程序继续执行
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }else{
            logger.info("有效设备列表为空!");
        }
    }

    //获取G代码文件的信息，获取文件的最近修改时间
    public synchronized void publish_progmap_metadata(String machineID, List<String> list){
        String topic = "Query/Request/"+machineID;
        List<String> list_dup = new ArrayList<>();
        String paramID = redisService.get_paramID_from_redis(machineID,"FILE");
        for(int index=0;index<list.size();index++) {
            list_dup.add("\""+list.get(index)+"\"");
        }
        String payload = "{\"ids\":[{\"id\":\""+paramID+"\",\"params\":{\"operation\":\"get_attributes\",\"keys\":"+list_dup+"}}]}";
        logger.info("publish:request for prog info!"+list_dup);
        this.mqttGateway.sendToMqtt(payload,topic);
    }

    //获取G代码文件内容
    public synchronized void publish_prog_gfile(String machineID,String prog_name){
        String paramID = redisService.get_paramID_from_redis(machineID,"FILE");
        String topic = "Query/Request/"+machineID;
        String payload = "{\"ids\":[{\"id\":\""+paramID+"\",\"params\":{\"operation\":\"get_value\",\"keys\":[\""+prog_name+"\"],\"offset\":0,\"length\":1024}}]}";
        logger.info("publish:request for prog content!");
        this.mqttGateway.sendToMqtt(payload,topic);
    }
}
